/**
 *
 */
package hichecker.ui.components.custom_table.table_cell_editor;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.EventObject;

import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JTable;
import javax.swing.JTextField;

/**
 *
 */
abstract public class AbstractTableCellEditor extends DefaultCellEditor{

	protected JTextField comp;
	protected boolean resetText;

	public AbstractTableCellEditor() {
		super(new JTextField());
		comp = (JTextField) getComponent();
		comp.setBorder(BorderFactory.createLineBorder(Color.BLACK));
	}

	@Override
	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
			int row, int column) {
		comp.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		comp.setText(resetText ? "" : value == null ? "" : "" + value);

		return comp;
	}

	@Override
	public Object getCellEditorValue() {
		return comp.getText();
	}

	@Override
	public boolean isCellEditable(EventObject anEvent) {
	    if (anEvent instanceof MouseEvent) {
	    	resetText = false;
			return ((MouseEvent)anEvent).getClickCount() >= clickCountToStart;
	    }
	    resetText = anEvent instanceof KeyEvent && ((KeyEvent) anEvent).getKeyCode() != KeyEvent.VK_F2;
	    return true;
	}

	@Override
	public boolean stopCellEditing() {
		boolean valid = isValidInput();
		if (!valid) {
			comp.setBorder(BorderFactory.createLineBorder(Color.RED));
			return false;
		}
		comp.setText(getModifiedInput());
		fireEditingStopped();
		return true;
	}

	abstract public boolean isValidInput();

	abstract protected String getModifiedInput();

}
